package com.GlobalPaint.app.ui.location;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.GlobalPaint.app.R;
import com.GlobalPaint.app.bean.GisBean;
import com.GlobalPaint.app.bean.ReturnStatusResultEntity;
import com.GlobalPaint.app.bean.guiJiBean;
import com.GlobalPaint.app.utils.Constants;
import com.GlobalPaint.app.utils.DataManager;
import com.GlobalPaint.app.utils.UiUtil;
import com.GlobalPaint.app.widget.CustomDatePicker;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MapViewLayoutParams;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.GlobalPaint.app.R.drawable.qqq;

public class FriendsLocationActivity extends AppCompatActivity {

    @BindView(R.id.iv_goback)
    ImageView ivGoback;
    @BindView(R.id.tv_common_center)
    TextView tvCommonCenter;
    @BindView(R.id.bt_front)
    Button btFront;
    @BindView(R.id.bt_queen)
    Button btQueen;
    @BindView(R.id.tv_fresh)
    TextView tvFresh;
    private int userId;
    private GisBean gisBean;
    private guiJiBean guijiBean;
    private BitmapDescriptor bitmap2;//当前点
    private BitmapDescriptor bitmap;//起点
    private BitmapDescriptor bitmap1;//终点
    private MapView mMapView;//MapView的控件
    private BaiduMap mBaiduMap;
    private View popView;
    private TextView tv_title;
    private LatLng dxu;
    private String now;
    private String now1;
    private CustomDatePicker customDatePicker2;//开始时间
    private CustomDatePicker customDatePicker1;//结束时间
    private String kssj;
    private String jssj;
    private static final int GET_GIS = 0x0003;
    private static final int GET_GUIJI = 0x0004;
    private Handler mhandler = new Handler() {
        public void handleMessage(Message message) {
            switch (message.what) {
                case GET_GIS:
                    String url = Constants.JASON_SERVICE_URL + "Gis/queryMy?userid=" + userId;
                    DataManager.getInst().getHttpRequestJsonClass(url, DataManager.userEntity.getCookie(), GisBean.class, new DataManager.Callback() {
                        @Override
                        public void onSuccess(Object o) {
                            gisBean = (GisBean) o;
                            if (gisBean.getStatus() == 1) {
                                if(gisBean.getData()!=null){
                                    if(gisBean.getData().getLat()!=0){
                                        dxu = new LatLng(gisBean.getData().getLat(), gisBean.getData().getLng());
                                        getlaLng(gisBean.getData().getLat(), gisBean.getData().getLng());
                                        initPopView(dxu);
                                    }

                                }


                            }
                        }

                        @Override
                        public void onFailure(ReturnStatusResultEntity error) {

                            //Toast.makeText(FriendsLocationActivity.this,gisBean.getMsg(),Toast.LENGTH_LONG).show();
                        }
                    });
                    break;
                case GET_GUIJI:
                    String url1 = Constants.JASON_SERVICE_URL + "Gis/query?userid=" + userId
                            + "&beginTime=" + kssj + "&endTime=" + jssj;
                    DataManager.getInst().getHttpRequestJsonClass(url1, DataManager.userEntity.getCookie(), guiJiBean.class, new DataManager.Callback() {
                        @Override
                        public void onSuccess(Object o) {
                            guijiBean = (guiJiBean) o;
                            if (guijiBean.getStatus() == 1) {
                                if (guijiBean.getData().size() > 1) {
                                    getweizhi(guijiBean.getData());
                                    setCentreMark(guijiBean.getData());
                                }
                            } else {
                                Toast.makeText(FriendsLocationActivity.this, guijiBean.getMsg(), Toast.LENGTH_LONG).show();
                            }

                        }

                        @Override
                        public void onFailure(ReturnStatusResultEntity error) {

                            // Toast.makeText(FriendsLocationActivity.this,guijiBean.getMsg(),Toast.LENGTH_LONG).show();
                        }
                    });
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friends_location);
        ButterKnife.bind(this);
        tvFresh.setVisibility(View.VISIBLE);
        tvFresh.setText("查看轨迹");
        userId = getIntent().getIntExtra("userid", 0);
        SimpleDateFormat nowft = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        String Front = nowft.format(new Date());
        SimpleDateFormat nowqn = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String queen = nowqn.format(new Date());
        btFront.setText(Front + " 00:00");
        btQueen.setText(queen);
        kssj = Front + " 00:00:00";
        jssj = queen + ":59";
        initView();
        initDatePicker();
    }

    private void initView() {
        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.bmapView);
        popView = View.inflate(FriendsLocationActivity.this, R.layout.pop_view1, null);
        tv_title = (TextView) popView.findViewById(R.id.tv_title);
        //获取baidumap对象
        mBaiduMap = mMapView.getMap();
        // 设置可改变地图位置
        mBaiduMap.setMyLocationEnabled(true);

        tvCommonCenter.setText("好友轨迹");
        mhandler.sendEmptyMessage(GET_GIS);
      //  mhandler.sendEmptyMessage(GET_GUIJI);
    }

    private void getlaLng(double lat, double lng) {

        MapStatusUpdate loc = MapStatusUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 13);
        mBaiduMap.setMapStatus(loc);
        LatLng point2 = new LatLng(lat, lng);
        //构建Marker图标
        bitmap2 = BitmapDescriptorFactory
                .fromResource(qqq);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option2 = new MarkerOptions()
                .position(point2)
                .icon(bitmap2);
        mBaiduMap.addOverlay(option2);

    }

    private void initPopView(LatLng dxu) {
        popView.setVisibility(View.GONE);
        MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(dxu);
        mBaiduMap.setMapStatus(update);
        update = MapStatusUpdateFactory.zoomBy((4));
        mBaiduMap.setMapStatus(update);
        mBaiduMap.setOnMapTouchListener(new BaiduMap.OnMapTouchListener() {
            /**
             * 当用户触摸地图时回调函数
             * @param event 触摸事件
             */
            public void onTouch(MotionEvent event) {
                mBaiduMap.hideInfoWindow();//隐藏消息窗
                popView.setVisibility(View.GONE);
            }
        });
        if (popView.getParent() == null)
            mMapView.addView(popView, createLayoutParams(dxu));

        /*mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                updatePopView(marker);
                if (marker.getIcon() == bitmap) {
                    tv_title.setText("dddd");
                } else if (marker.getIcon() == bitmap1) {

                } else if (marker.getIcon() == bitmap2) {

                }
                return true;
            }
        });*/
    }

    private void updatePopView(final Marker marker) {
        mMapView.updateViewLayout(popView, createLayoutParams(marker.getPosition()));
        popView.setVisibility(View.VISIBLE);
        // 显示标志的标题
    }

    private MapViewLayoutParams createLayoutParams(LatLng xzPos) {
        MapViewLayoutParams params = new MapViewLayoutParams.Builder()
                .layoutMode(MapViewLayoutParams.ELayoutMode.mapMode)    // 坐标类型为经纬度的类型
                .position(xzPos)    // 指定View的位置
                .yOffset(UiUtil.dp2px(-28))       // 指定View在y方向的偏移量
                .build();
        return params;
    }

    private void getweizhi(List<guiJiBean.DataBean> data) {
        LatLng point = new LatLng(data.get(0).getLat(), data.get(0).getLng());
        LatLng point1 = new LatLng(data.get(data.size() - 1).getLat(), data.get(data.size() - 1).getLng());
        //构建Marker图标
        bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.baidu_qidian);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);
        mBaiduMap.addOverlay(option);
        //构建Marker图标终点
        bitmap1 = BitmapDescriptorFactory
                .fromResource(R.drawable.baidu_zhongdian);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option1 = new MarkerOptions()
                .position(point1)
                .icon(bitmap1);
        //在地图上添加Marker，并显示
        mBaiduMap.addOverlay(option1);
    }

    private void setCentreMark(List<guiJiBean.DataBean> data) {
        //构造纹理资源
        BitmapDescriptor custom1 = BitmapDescriptorFactory
                .fromResource(R.drawable.baiduluxian);
        //构造纹理队列
        List<BitmapDescriptor> customList = new ArrayList<BitmapDescriptor>();

        List<LatLng> points = new ArrayList<LatLng>();
        List<Integer> index = new ArrayList<Integer>();

        for (int i = 0; i < data.size(); i++) {
            customList.add(custom1);
            points.add(new LatLng(data.get(i).getLat(), data.get(i).getLng()));//点元素
            index.add(i);//设置该点的纹理索引
        }
//构造对象
        OverlayOptions ooPolyline = new PolylineOptions().width(15).color(0xAAFF0000).points(points).customTextureList(customList).textureIndex(index);
//添加到地图
        mBaiduMap.addOverlay(ooPolyline);
    }

    //选择时间
    private void initDatePicker() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        now1 = sdf1.format(new Date());
        now = sdf.format(new Date());
        customDatePicker2 = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间

                kssj = time + ":00";
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
                if (kssj == "" || jssj == null) {
                    jssj = now1 + " 23:59";
                }
                try {
                    Date dt1 = df.parse(kssj);
                    Date dt2 = df.parse(jssj);
                    if (dt1.getTime() > dt2.getTime()) {
                        Toast.makeText(FriendsLocationActivity.this, "开始时间应小于结束时间", Toast.LENGTH_LONG).show();
                        return;
                    }
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
                btFront.setText(time);
            }
        }, "2010-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker2.showSpecificTime(true); // 显示时和分
        customDatePicker2.setIsLoop(true); // 允许循环滚动

        customDatePicker1 = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间

                jssj = time + ":00";
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
                if (kssj == "" || jssj == null) {
                    kssj = now1 + " 00:00";
                }
                try {
                    Date dt1 = df.parse(kssj);
                    Date dt2 = df.parse(jssj);
                    if (dt1.getTime() > dt2.getTime()) {
                        Toast.makeText(FriendsLocationActivity.this, "结束时间不应小于开始时间", Toast.LENGTH_LONG).show();
                        return;
                    }
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
                btQueen.setText(time);
            }
        }, "2010-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker1.showSpecificTime(true); // 显示时和分
        customDatePicker1.setIsLoop(true); // 允许循环滚动
    }

    @OnClick({R.id.iv_goback, R.id.bt_front, R.id.bt_queen,R.id.tv_fresh})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_goback:
                finish();
                break;
            case R.id.bt_front:

                customDatePicker2.show(now1 + " 00:00");
                break;
            case R.id.bt_queen:

                customDatePicker1.show(now);
                break;
            case R.id.tv_fresh:
                mBaiduMap.clear();
                mhandler.sendEmptyMessage(GET_GIS);
                mhandler.sendEmptyMessage(GET_GUIJI);
                break;
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
